Refactorizar estructura if else

Descripcion

Como refactorizar una estructura if-else para que sea mas facil de leer y mejor entendible.

Metodo
Refactor con polimorfismo Robert C. Martin

Ejemplo 1

El siguiente código:

public static boolean isLeapYear(final int yyyy) {
    if ((yyyy % 4) != 0) {
        return false;
    }
    else if ((yyyy % 400) == 0) {
        return true;
    }
    else if ((yyyy % 100) == 0) {
        return false;
    }
    else {
        return true;
    }
}

Podemos refactorizarlo como:

public static boolean isLeapYear(int year) {
    boolean fourth = year  4 == 0;
    boolean hundredth = year % 100 == 0;
    boolean fourHundredth = year % 400 == 0;
    return fourth && (!hundredth || fourHundredth);
}

Ejemplo 2

Código completo

Código sin refactorizar:

public class ThingBad {

    public String name;

    public String getType(){
        if(this.name.equals("gato")){
            return "animal";
        }else if(this.name.equals("cactus")){
            return"plant";
        }else if(this.name.equals("car")){
            return "object";
        }else{
            return "unknown";
        }
    }
}

Código refactorizado 1:

public class ThingGood {

  private String name;
  private static final Map<String, String> things = new HashMap<>();

  ThingGood(){
      things.put("gato", "animal");
      things.put("cactus", "plant");
      things.put("car", "object");
  }

  public String getName() {
      return name;
  }

  public void setName(String name) {
      this.name = name;
  }

  public void printType(){
      System.out.println(this.getType());
  }

  private String getType(){
      String result;
      result = things.get(this.name);

      return (result == null) ? "unknown" : result;
  }
}

Código refactorizado 2:

public class Thing {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void printType(){
        System.out.println(this.getType());
    }

    private String getType() {
        if(this.name.equals("gato")) return "animal";
        if(this.name.equals("cactus")) return"plant";
        if(this.name.equals("car")) return "object";

        return "unknown";
    }
}

En C# podemos hacer una implementacion con switch, de una manera muy simplificada:

String nombre = "gato";
String tipo;

tipo = nombre switch
{
    "gato" => "animal",
    "cactus" => "planta",
    "coche" => "objeto",
    _ => "desconocido"
};

WriteLine(tipo);
Tags

Clean Code | if else